package dmir.reaction.publico.parsers;

import java.util.HashMap;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class FindEntitiesParser extends DefaultHandler {

	boolean getDate = false;
	boolean getEntities = false;
	String data = new String();
	String year_month = new String();
	
	public HashMap<String,Integer> pessoa = new HashMap<String,Integer>();
	public HashMap<String,Integer> local = new HashMap<String,Integer>();
	public HashMap<String,Integer> organizacao = new HashMap<String,Integer>();

	public FindEntitiesParser(String year_month) {
		super();
		this.year_month = year_month;
	}

	public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {

		if (qName.equalsIgnoreCase("date")) {
			getDate = true;
			this.data = "";
		}

		if (qName.equalsIgnoreCase("PESSOA") && getEntities)
			this.data = "";

		if (qName.equalsIgnoreCase("ORGANIZACAO") && getEntities) 
			this.data = "";
		 
		if (qName.equalsIgnoreCase("LOCAL") && getEntities)
			this.data = "";
	}

	public void characters(char ch[], int start, int length)
			throws SAXException {

		if (getDate || getEntities) {
			this.data = new String(ch, start, length);
		}
	}

	public void endElement(String uri, String localName, String qName) throws SAXException {

		if (getDate) {
			this.getDate = false;
			if (this.data.matches(year_month + ".*")) {
				//System.out.println(this.data);
				getEntities = true;
			}
		}
		

		if (qName.equalsIgnoreCase("PESSOA") && getEntities) {
			
			try {
				pessoa.put(data.trim(), pessoa.get(data)+1);
			}
			catch (Exception e) {
				pessoa.put(data, 1);
			}
		}

		
		if (qName.equalsIgnoreCase("ORGANIZACAO") && getEntities) {
			try {
				organizacao.put(data.trim(), organizacao.get(data)+1);
			}
			catch (Exception e) {
				organizacao.put(data, 1);
			}
		}
		
		
		if (qName.endsWith("LOCAL") && getEntities) {
			try {
				local.put(data.trim(), local.get(data)+1);
			}
			catch (Exception e) {
				local.put(data, 1);
			}
		}

		if (qName.equalsIgnoreCase("article")) {
			this.getDate = false;
			this.getEntities = false;
		}
	}
}